//
//  RefundDetailViewController.m
//  B2C
//
//  Created by 李小龙 on 2017/8/17.
//  Copyright © 2017年 lixiaolong. All rights reserved.
//

#import "RefundDetailViewController.h"
#import "OrderDetailTableViewCell.h"
#import "RefundViewController.h"
#import "OpinionViewController.h"
#import "OthersMemberInfoModel.h"
//#import "OthersStoreViewController.h"
//#import "GoodDetailViewController.h"

@interface RefundDetailViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomHLayout;
@end

@implementation RefundDetailViewController
#pragma mark - UIViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"退款详情";
    
    [self.tableView clearExtendCellLine];
    [self getNetData];
}
#pragma mark - 网络请求
- (void)getNetData {
    // 根据订单id获取订单详细信息
    NSString *urlStr;
    if (self.type == RefundFromTypeMineStore) {
        urlStr = URL_Get_Shop_Refund_Order_Detail;
    } else {
        urlStr = URL_Get_Refund_Order_Detail;
    }
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    [MYAFNetworking POST:urlStr parameters:@{@"ogid":self.detailModel.ogid} success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if ([responseObject[@"code"] isEqualToString:@"200"]) {
            self.detailModel = [OrderModel mj_objectWithKeyValues:responseObject[@"data"]];
            [self.tableView reloadData];
            [self createBottomView];
        } else {
            [MBProgressHUD showError:self.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [MBProgressHUD showError:self.view title:@"" code:@"" animated:YES];
    }];
}
#pragma mark - action
- (void)cancelRefund {
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    [MYAFNetworking POST:URL_Delete_Refund parameters:@{@"ogid":self.detailModel.ogid} success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if ([responseObject[@"code"] isEqualToString:@"200"]) {
            [MBProgressHUD myShowHUDAddedTo:self.view labelText:@"已提交取消申请" animated:YES];
            [self popToRootViewController];
        } else {
            [MBProgressHUD showError:self.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [MBProgressHUD showError:self.view title:@"" code:@"" animated:YES];
    }];
}
- (void)refundAction {
    // 点击“重新申请”按钮时跳转
    RefundViewController *refundVC = [[RefundViewController alloc] init];
    refundVC.detailModel = self.detailModel;
    [self.navigationController pushViewController:refundVC animated:YES];
}
- (void)agreeRefund:(OrderModel *)model feedback:(NSString *)feedback {
    NSMutableDictionary * parameters = [[NSMutableDictionary alloc] init];
    [parameters setObject:model.ogid forKey:@"ogid"];
    if (TextIsNotNil(feedback)) {
        [parameters setObject:@"3" forKey:@"rstatus"];
        [parameters setObject:feedback forKey:@"feedback"];
    } else {
        [parameters setObject:@"2" forKey:@"rstatus"];
    }
    
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    [MYAFNetworking POST:URL_Shop_Save_Refund parameters:parameters success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if ([responseObject[@"code"] isEqualToString:@"200"]) {
            if (self.block) {
                self.block(YES);
            }
            [self disMissSelf];
        } else {
            [MBProgressHUD showError:self.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [MBProgressHUD showError:self.view title:@"" code:@"" animated:YES];
    }];
}
- (void)rejectRefund:(OrderModel *)model {
    OpinionViewController *opinionVC = [[OpinionViewController alloc] init];
    opinionVC.type = OpinionTypeRefund;
    opinionVC.block = ^(NSString *reason) {
        [self agreeRefund:model feedback:reason];
    };
    [self.navigationController pushViewController:opinionVC animated:YES];
}
/**
 联系买家
 */
- (void)contactBuyer:(OrderModel *)model {
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters safeSetObject:model.mid forKey:@"mid"];
    __weak typeof(self) weakSelf = self;
    [MYAFNetworking POST:URL_Get_Other_Member_Info parameters:parameters success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        NSDictionary *responseDic = responseObject;
        NSString *code = [responseDic safeObjectForKey:@"code"];
        if ([code isEqualToString:@"200"]) {
            NSDictionary *modelDic = [responseDic safeJsonObjectForKey:@"data"];
            OthersMemberInfoModel *model = [OthersMemberInfoModel mj_objectWithKeyValues:modelDic];
            /*
            // 更新本地融云个人数据
            RCUserInfo *updatedUserInfo =
            [[RCUserInfo alloc] initWithUserId:model.mid name:model.mnickname portrait:model.mimg];
            [[RCIM sharedRCIM] refreshUserInfoCache:updatedUserInfo withUserId:updatedUserInfo.userId];
            
            // 跳转到聊天界面
            ChatViewController *chatVC = [[ChatViewController alloc] init];
            // 会话类型
            chatVC.conversationType = ConversationType_PRIVATE;
            // targetID
            chatVC.targetId = model.mid;
            // title
            chatVC.title = model.mnickname;
            // 多商品，不显示商品链接
            //// 传入商品链接
            //charVC.gid = item.gid;
            //charVC.gname = item.gname;
            [weakSelf.navigationController pushViewController:chatVC animated:YES];
            */
        } else {
            [MBProgressHUD showError:weakSelf.view title:@"" code:code animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        [MBProgressHUD showError:weakSelf.view title:@"" code:@"" animated:YES];
    }];
}
// 哈哈商城
- (void)getCustomerInfo:(OrderModel *)itemModel {
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    //    [parameters safeSetObject:itemModel.shop.mid forKey:@"mid"];
    __weak typeof(self) weakSelf = self;
    [MYAFNetworking POST:URL_Get_Customer parameters:parameters success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        NSDictionary *responseDic = responseObject;
        NSString *code = [responseDic safeObjectForKey:@"code"];
        if ([code isEqualToString:@"200"]) {
            NSDictionary *data = [responseDic safeJsonObjectForKey:@"data"];
            /*
            CustomerModel *customerModel = [CustomerModel mj_objectWithKeyValues:data];
            // 更新本地融云个人数据
            RCUserInfo *updatedUserInfo =
            [[RCUserInfo alloc] initWithUserId:customerModel.rcid name:customerModel.uname portrait:customerModel.img];
            [[RCIM sharedRCIM]
             refreshUserInfoCache:updatedUserInfo
             withUserId:updatedUserInfo.userId];
            
            // 跳转到聊天界面
            ChatViewController *chatVC = [[ChatViewController alloc] init];
            // 会话类型
            chatVC.conversationType = ConversationType_PRIVATE;
            // targetID
            chatVC.targetId = updatedUserInfo.userId;
            // title
            chatVC.title = updatedUserInfo.name;
            //// 传入商品链接
            //charVC.gid = itemModel.gid;
            //charVC.gname = itemModel.gname;
            [weakSelf.navigationController pushViewController:chatVC animated:YES];
            */
        } else {
            [MBProgressHUD showError:weakSelf.view title:@"" code:code animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        [MBProgressHUD showError:weakSelf.view title:@"" code:@"" animated:YES];
    }];
}
/**
 查看他人店铺
 */
- (void)clickHeaderCheckStore:(OrderModel *)model {
    NSLog(@"查看他人店铺");
    /*
    ShopModel *shopModel = model.shop;
    if (![shopModel.sid isEqualToString:@"0"]) {
//        OthersStoreViewController *otherStoreVC = [[OthersStoreViewController alloc] init];
//        otherStoreVC.mid = shopModel.mid;
//        [self.navigationController pushViewController:otherStoreVC animated:YES];
    }
     */
}

- (void)removeFourthBackViewSubView {
    for (UIView *view in self.bottomView.subviews) {
        if ([view isKindOfClass:[UIButton class]]) {
            if (view.tag != 10000) {
                [view removeFromSuperview];
            } else {
                NSLog(@"%@",view);
            }
        }
    }
}
- (void)createBottomView {
    // 0已提交，1已退款，2卖家同意，3退款驳回
    NSInteger rstatus = self.detailModel.refund.lastObject.rstatus.integerValue;
    if (rstatus == 0 || rstatus == 3) {
        CGFloat buttonY = 9;
        CGFloat buttonW = 75;
        CGFloat kong = 5;
        [self removeFourthBackViewSubView];
        
        NSString *buttonTitle;
        SEL buttonAction;
        if (rstatus == 0) {
            buttonTitle = @"取消退款";
            buttonAction = @selector(cancelRefund);
        } else {
            buttonTitle = @"重新申请";
            buttonAction = @selector(refundAction);
        }
        OrderHalfButton *button = [OrderHalfButton orderButtonWithType:OrderButtonTypeDelete frame:CGRectMake(ScreenWidth-(kong+buttonW), buttonY, buttonW, self.bottomView.height-buttonY*2) buttonTitle:buttonTitle color:[UIColor ThemeColor] borderColor:[UIColor ThemeColor]];
        
        [button addTarget:self action:buttonAction forControlEvents:UIControlEventTouchUpInside];
        [self.bottomView addSubview:button];
    } else {
        self.bottomHLayout.constant = 0;
        [self.view layoutIfNeeded];
        [self.bottomView setHidden:YES];
    }
}
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (section) {
        case 0:
            return 2;
        case 1:
            return 1;
        case 2:
            // 0已提交，1已退款，2卖家同意，3退款驳回
            if (self.detailModel.refund.lastObject.rstatus.integerValue == 3) {
                return 1+1;//self.detailModel.goods.count
            }
            return 1;//self.detailModel.goods.count
        default:
            return 0;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    OrderType type;
    // 0已提交，1已退款，2卖家同意，3退款驳回
    if (self.type == RefundFromTypeMineStore) {
        switch (self.detailModel.refund.lastObject.rstatus.integerValue) {
            case 0:
                type = OrderTypeMineStoreRefund;
                break;
            case 1:
                type = OrderTypeMineStoreRefundSuccess;
                break;
            case 2:
                type = OrderTypeMineStoreRefundFailure;
                break;
            case 3:
                type = OrderTypeMineStoreRefundDismiss;
                break;
            default:
                type = OrderTypeMineStoreRefund;
                break;
        }
    } else {
        switch (self.detailModel.refund.lastObject.rstatus.integerValue) {
            case 0:
                type = OrderTypeRefund;
                break;
            case 1:
                type = OrderTypeRefundSuccess;
                break;
            case 2:
                type = OrderTypeRefundFailure;
                break;
            case 3:
                type = OrderTypeRefundDismiss;
                break;
            default:
                type = OrderTypeRefund;
                break;
        }
    }
    
    OrderDetailTableViewCell *cell = [OrderDetailTableViewCell refundDetailCellWith:tableView indexPath:indexPath count:1 type:type];//self.detailModel.goods.count
    [cell updateRefundDetailCellWith:self.detailModel indexPath:indexPath count:1 type:type];//self.detailModel.goods.count
    cell.detailBlock = ^(DetailCellClickType type) {
        switch (type) {
            case DetailCellClickTypeRefund:
            {
                NSLog(@"退款");
            } break;
            case DetailCellClickTypeRefundCancel:
            {
                NSLog(@"取消退款");
                [self cancelRefund];
            } break;
            case DetailCellClickTypeRefundAgain:
            {
                NSLog(@"重新申请");
                [self refundAction];
            } break;
            case DetailCellClickTypeRefundDone:
            {
                NSLog(@"退款完成");
                
            } break;
            case DetailCellClickTypeStoreRefundAgree:
            {
                NSLog(@"我的店铺->同意申请");
                [self agreeRefund:self.detailModel feedback:nil];
            } break;
            case DetailCellClickTypeStoreRefundReject:
            {
                NSLog(@"我的店铺->拒绝退款");
                [self rejectRefund:self.detailModel];
            } break;
            case DetailCellClickTypeService:
            {
                switch (self.type) {
                    case RefundFromTypeSelfOrder:
                    {
                        if ([self.detailModel.sid isEqualToString:@"0"]) {
                            NSLog(@"联系客服");
                            [self goToServiceChat];
                            break;
                            // 自营
                            [self getCustomerInfo:self.detailModel];
                        } else {
                            // 个人、企业
                            [self contactBuyer:self.detailModel];
                        }
                    } break;
                    case RefundFromTypeMineStore:
                    {
                        NSLog(@"联系买家");
                        [self contactBuyer:self.detailModel];
                    } break;
                    default:
                        break;
                }
            } break;
            default:
                break;
        }
    };
    return cell;
}
#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//    if (indexPath.section == 1 && indexPath.row == 0) {
//        [self clickHeaderCheckStore:self.detailModel];
//        return;
//    }
    
    if (self.type == RefundFromTypeSelfOrder) {
        if (indexPath.section == 1) {
            NSLog(@"跳转商品详情");
//            GoodDetailViewController *goodVC = [[GoodDetailViewController alloc] init];
//            goodVC.gid = self.detailModel.gid;
//            [self.navigationController pushViewController:goodVC animated:YES];
        }
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.section) {
        case 0:
            switch (indexPath.row) {
                case 0:
                    return 70;
                case 1:
                    if (self.detailModel.refund.lastObject.rstatus.integerValue == 3) {
                        return UITableViewAutomaticDimension;
                    }
                    return 44;
                default:
                    return 0;
            }
        case 1:
            return 112;
        case 2:
            if (self.detailModel.refund.lastObject.rstatus.integerValue == 3) {
                if (indexPath.row == 0) {//self.detailModel.goods.count
                    return 44;
                } else {
                    return 90;
                }
            } else {
                return 90;
            }
        default:
            return 0;
    }
}
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 100;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section < 2) {
        return 10;
    }
    return 0.001;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 10)];
    [view setBackgroundColor:[UIColor grayfaColor]];
    return view;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
